using MySql.Data.MySqlClient;
using Spire.Pdf.Exporting.XPS.Schema;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Publicuse.DBCore;
using Publicuse.Entity;
using Publicuse.Entity.AttributeUtil;
using Publicuse.Entity.AttributeUtil.Validate;
using Publicuse.Util;
using ServiceStack;

namespace Publicuse.DBCore.MySql
{
    /// <summary>
    /// MySql数据库操作类
    /// </summary>
    public class MySqlInstance
    {
        private string connstr;

        private static object locker = new object();

        private static MySqlInstance mySqlInstance = null;

        static MySqlInstance()
        {
            mySqlInstance = new MySqlInstance();
        }

        public static MySqlInstance GetInstance
        {
            get { return mySqlInstance; }
        }

        /// <summary>
        /// 数据库实例字段初始化
        /// </summary>
        /// <param name="constr"></param>
        public void Init(string constr)
        {
            if (string.IsNullOrEmpty(constr))
                return;

            this.connstr = constr;
        }

        /// <summary>
        /// 设置连接数据库字符串
        /// </summary>
        /// <param name="writeAndRead"></param>
        /// <returns></returns>
        private string SetConnecStr(WriteAndReadEnum writeAndRead)
        {
            string constr = string.Empty;
            switch (writeAndRead)
            {
                case WriteAndReadEnum.Write:
                    {
                        constr = this.connstr.Split('|')[0];
                    }
                    break;
                case WriteAndReadEnum.Read:
                    {
                        var newstrs = this.connstr.Split('|')[1].Split(',');
                        int index = new Random().Next(0, newstrs.Length - 1);
                        constr = newstrs[index];
                    }
                    break;
            }
            return constr;
        }

        /// <summary>
        /// 存储过程参数封装
        /// </summary>
        /// <param name="sqlcmd"></param>
        /// <param name="param"></param>
        /// <param name="sqlParamsType"></param>
        /// <returns></returns>
        private bool parameterCom(IDbCommand sqlcmd, object param, SqlParamsType sqlParamsType)
        {
            if (param == null)
            {
                return true;
            }
            if (!(param is object[]))
            {
                return false;
            }
            if (sqlParamsType == SqlParamsType.Default)
            {
                object[] array = param as object[];
                if (array.Length % 2 != 0)
                {
                    return false;
                }
                for (int i = 0; i < array.Length; i += 2)
                {
                    MySqlParameter mySqlParameter = new MySqlParameter();
                    mySqlParameter.ParameterName = array[i].ToString();
                    mySqlParameter.Value = array[i + 1];
                    if (array[i + 2] != null)
                    {
                        mySqlParameter.Direction = (array[i + 2]).ToString() == "1" ? ParameterDirection.Input : ParameterDirection.Output;
                    }
                    sqlcmd.Parameters.Add(mySqlParameter);
                }
            }
            else if (sqlParamsType == SqlParamsType.Params)
            {
                object[] array = param as object[];
                foreach (var pi in array)
                    sqlcmd.Parameters.Add(pi);
            }

            return true;
        }

        /// <summary>
        /// 通用CUD操作
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entity"></param>
        /// <param name="cUDType"></param>
        /// <param name="exception"></param>
        /// <param name="sql"></param>
        /// <returns>返回操作结果</returns>
        public int CUDEntity<T>(T entity, CUDType cUDType, out string exception, string sql = null) where T : new()
        {
            exception = null;
            var sqlParameter = new MySqlParameter[] { };
            CURDModel cURDModel = null;
            if (string.IsNullOrEmpty(sql))
            {
                switch (cUDType)
                {
                    case CUDType.Add:
                        {
                            sqlParameter = SqlCacheBuilder<T>.GSqlCacheBuilder.GetSql(SqlCacheBuildertType.MySqlInser, entity, out exception, out sql).GetMySqlParameters;
                        }
                        break;
                    case CUDType.Update:
                        {
                            sqlParameter = SqlCacheBuilder<T>.GSqlCacheBuilder.GetSql(SqlCacheBuildertType.MySqlUpdate, entity, out exception, out sql).GetMySqlParameters;
                        }
                        break;
                    case CUDType.Delete:
                        {
                            sqlParameter = SqlCacheBuilder<T>.GSqlCacheBuilder.GetSql(SqlCacheBuildertType.MySqlDelete, entity, out exception, out sql).GetMySqlParameters;
                        }
                        break;
                }
                cURDModel = new CURDModel() { sqlParamsType = SqlParamsType.Params, cUDType = cUDType };
            }
            else
            {
                cURDModel = new CURDModel() { sqlParamsType = SqlParamsType.Default, cUDType = cUDType };
            }
            return ExecuteNonQuery(sql, sqlParameter, cURDModel, false, out exception);
        }

        /// <summary>
        /// 批量新增修改
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entity"></param>
        /// <param name="cUDType"></param>
        /// <param name="exception"></param>
        /// <param name="sql"></param>
        /// <returns></returns>
        public List<int> CUDEntity<T>(List<T> entitys, CUDType cUDType, out string exception, string sql = null) where T : new()
        {
            exception = null;
            var sqlParameter = new MySqlParameter[] { };
            CURDModel cURDModel = null;
            List<MySqlParameter[]> listsqlParameter = new List<MySqlParameter[]>();
            List<string> listsql = new List<string>();
            if (string.IsNullOrEmpty(sql))
            {
                foreach (var entity in entitys)
                {
                    switch (cUDType)
                    {
                        case CUDType.Add:
                            {
                                sqlParameter = SqlCacheBuilder<T>.GSqlCacheBuilder.GetSql(SqlCacheBuildertType.MySqlInser, entity, out exception, out sql).GetMySqlParameters;
                            }
                            break;
                        case CUDType.Update:
                            {
                                sqlParameter = SqlCacheBuilder<T>.GSqlCacheBuilder.GetSql(SqlCacheBuildertType.MySqlUpdate, entity, out exception, out sql).GetMySqlParameters;
                            }
                            break;
                        case CUDType.Delete:
                            {
                                sqlParameter = SqlCacheBuilder<T>.GSqlCacheBuilder.GetSql(SqlCacheBuildertType.MySqlDelete, entity, out exception, out sql).GetMySqlParameters;
                            }
                            break;
                    }
                    listsqlParameter.Add(sqlParameter);
                    listsql.Add(sql);
                }
                cURDModel = new CURDModel() { sqlParamsType = SqlParamsType.Params, cUDType = cUDType };
            }
            else
            {
                cURDModel = new CURDModel() { sqlParamsType = SqlParamsType.Default, cUDType = cUDType };
            }
            return ExecuteNonQuery(listsql, listsqlParameter, cURDModel, false, out exception);
        }

        /// <summary>
        /// 初始化数据库连接
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="msg"></param>
        /// <param name="action"></param>
        /// <returns></returns>
        private T InitConnction<T>(out string msg, WriteAndReadEnum writeAndRead, Func<MySqlCommand, T> action)
        {
            msg = string.Empty;
            try
            {
                using (MySqlConnection con = new MySqlConnection(SetConnecStr(writeAndRead)))
                {
                    MySqlCommand cmd = new MySqlCommand();
                    con.Open();
                    cmd.Connection = con;
                    var result= action.Invoke(cmd);
                    return result;
                }
            }
            catch (Exception ex)
            {
                msg = ex.Message;
                //LogUtil.GetInstance.WriteLogOld("连接MySql失败", ex.Message + "|" + this.connstr, true);
                return default(T);
            }
        }

        /// <summary>
        /// 就是通过json字符串找出更新的字段
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="json"></param>
        /// <param name="id"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public int Update<T>(string json, int id,out string msg)
        {
            msg = string.Empty;
            try
            {
                var result=this.InitConnction(out msg, WriteAndReadEnum.Write, cmd =>
                {
                    Type type = typeof(T);
                    T t = Newtonsoft.Json.JsonConvert.DeserializeObject<T>(json);
                    string stringSet = string.Join(",", type.GetPropertiesInJson(json).Select(p => $"{p.GetMappingName()}=@{p.Name}"));
                    var keyId = TableAtributeUtil.GetPrimaryKey<T>();
                    string sql = $"update {type.GetMappingName()} set {stringSet} where keyId=@{keyId};";
                    var paraArray = type.GetPropertiesInJson(json).Select(p => new MySqlParameter($"@{p.Name}", p.GetValue(t) ?? DBNull.Value)).Append(new MySqlParameter($"@{keyId}", id)).ToArray();
                    cmd.CommandType =  CommandType.Text;
                    cmd.CommandText = sql;
                    cmd.Parameters.AddRange(paraArray);
                    return cmd.ExecuteNonQuery();
                });
                return result;
            }
            catch (Exception ex)
            {
                msg = ex.Message;
                //LogUtil.GetInstance.WriteLogOld("连接MySql失败", ex.Message + "|" + this.connstr, true);
                return 0;
            }
        }

        /// <summary>
        /// 批量操作
        /// </summary>
        /// <param name="sqlstr"></param>
        /// <param name="param"></param>
        /// <param name="cURDModel"></param>
        /// <param name="isproc"></param>
        /// <param name="exception"></param>
        /// <returns></returns>
        public List<int> ExecuteNonQuery(List<string> sqlstr, List<MySqlParameter[]> param, CURDModel cURDModel, bool isproc, out string exception)
        {
            exception = null;
            List<int> result = new List<int>();
            MySqlTransaction tran = null;

            result = InitConnction(out exception, WriteAndReadEnum.Write, (cmd) =>
             {
                 using (tran = cmd.Connection.BeginTransaction())
                 {
                     cmd.Transaction = tran;
                     var index = 0;
                     foreach (var sql in sqlstr)
                     {
                         cmd.CommandText = sql;
                         cmd.Parameters.Clear();
                         cmd.Parameters.AddRange(param[index]); ;
                         cmd.CommandType = (isproc ? CommandType.StoredProcedure : CommandType.Text);
                         var res = cURDModel.cUDType == CUDType.Add ? Convert.ToInt32(cmd.ExecuteScalar()) : cmd.ExecuteNonQuery();
                         if (res < 0)
                         {
                             if (tran != null)
                                 tran.Rollback();

                             result.Add(-1);
                         }
                         else
                         {
                             result.Add(res);
                         }
                         index++;
                     }
                     tran.Commit();
                     return result;
                 }
             });
            return result;
        }

        /// <summary>
        /// 执行SQL
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="msg"></param>
        /// <param name="func"></param>
        /// <returns></returns>
        public bool ExecuteSql(string sql, out string msg, Func<IDbCommand, bool> func)
        {
            msg = null;
            var result = InitConnction(out msg, WriteAndReadEnum.Write, cmd =>
             {
                 using (MySqlTransaction tran = cmd.Connection.BeginTransaction())
                 {
                     cmd.CommandText = sql;
                     cmd.Transaction = tran;
                     var res = func.Invoke(cmd);
                     if (res)
                         tran.Commit();
                     else
                         tran.Rollback();

                     return res;
                 }
             });
            return result;
        }

        /// <summary>
        /// 执行SQL
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="pairs"></param>
        /// <param name="msg"></param>
        /// <param name="func"></param>
        /// <returns></returns>
        public bool ExecuteSql(string sql, Dictionary<string,string> pairs, out string msg, ExcuteType type)
        {
            msg = null;
            var result = InitConnction(out msg, WriteAndReadEnum.Write, cmd =>
            {
                using (MySqlTransaction tran = cmd.Connection.BeginTransaction())
                {
                    cmd.Parameters.AddRange(pairs.Select(p => {

                        if (type == ExcuteType.In)
                        {
                            var vs = p.Value.Split(',');
                            var newvalue = string.Empty;
                            foreach (var item in vs)
                            {
                                newvalue += "'" + item + "',";
                            }
                            var Value = newvalue.TrimEnd(',');
                            return new MySqlParameter(string.Format("@{0}", p.Key), Value);
                        }
                        else
                        {
                            return new MySqlParameter(string.Format("@{0}", p.Key), p.Value);
                        }
                    }).ToArray());
                    var newsql = string.Empty;
                    var index = 0;
                    pairs.ForEach((key, value) =>
                    {
                        if (index == 0)
                        {
                            if (type == ExcuteType.Equal)
                            {
                                newsql = $" where {key}=@{key} ";
                            }
                            else if (type == ExcuteType.In)
                            {
                                newsql = $" where {key} in (@{key}) ";
                            }
                        }
                        else
                        {
                            if (type == ExcuteType.Equal)
                            {
                                newsql += $" and {key}=@{key} ";
                            }
                            else if (type == ExcuteType.In)
                            {
                                newsql += $" and {key} in(@{key}) ";
                            }
                        }
                        index++;
                    });
                    cmd.CommandText = sql + newsql;
                    cmd.Transaction = tran;
                    var res = cmd.ExecuteNonQuery()>=0;
                    if (res)
                        tran.Commit();
                    else
                        tran.Rollback();

                    return res;
                }
            });
            return result;
        }

        /// <summary>
        /// 执行批量SQL
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="pairs"></param>
        /// <param name="msg"></param>
        /// <param name="func"></param>
        /// <returns></returns>
        public bool ExecuteSql(List<Tuple<string, Dictionary<string, string>>> pairs, out string msg)
        {
            msg = null;
            var result = InitConnction(out msg, WriteAndReadEnum.Write, cmd =>
            {
                using (MySqlTransaction tran = cmd.Connection.BeginTransaction())
                {
                    var newsql = string.Empty;
                    var isPass = true;
                    pairs.ForEach(a =>
                    {
                        cmd.Parameters.AddRange(a.Item2.Select(p => new MySqlParameter(string.Format("@{0}", p.Key), p.Value)).ToArray());
                        var index = 0;
                        a.Item2.ForEach((key, value) =>
                        {
                            newsql = a.Item1;
                            if (index == 0)
                            {
                                newsql += $" where {key}=@{key} ";
                            }
                            else
                            {
                                newsql += $" and {key}=@{key} ";
                            }
                            index++;
                            cmd.Transaction = tran;
                            var res=cmd.ExecuteNonQuery()>=0;
                            if (!res)
                            {
                                isPass = false;
                            }
                        });
                    });
                    if (isPass)
                        tran.Commit();
                    else
                        tran.Rollback();
               
                    return isPass;
                }
            });
            return result;
        }


        /// <summary>
        /// 根据主键获取信息
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="Id"></param>
        /// <param name="exception"></param>
        /// <param name="t"></param>
        /// <returns></returns>
        public bool GetEntityById<T>(long Id, out string exception, out T t) where T : new()
        {
            t = new T();
            exception = null;
            var msg = string.Empty;
            t=InitConnction(out exception, WriteAndReadEnum.Read, cmd =>
            {
                var t = new T();
                Type type = typeof(T);
                var sqlParam = SqlCacheBuilder<T>.GSqlCacheBuilder.GetSql(SqlCacheBuildertType.MySqlQuery, default(T), out msg, out var sql, Id).GetMySqlParameter;
                cmd.CommandText = sql;
                cmd.Parameters.Add(sqlParam);
                var item = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                if (item.Read())
                {
                    foreach (var pi in type.GetPropertiesWithNoQuery())
                    {
                        pi.SetValue(t, item[pi.GetMappingName()] is DBNull ? null : item[pi.GetMappingName()]);
                    }
                }
                return t;
            });
            return string.IsNullOrEmpty(msg) ? true : false;
        }

        /// <summary>
        /// 查询列表信息
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="tablename"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="sqlWhere"></param>
        /// <param name="sortFile"></param>
        /// <param name="srotType"></param>
        /// <param name="count"></param>
        /// <param name="exception"></param>
        /// <param name="list"></param>
        /// <returns></returns>
        public bool GetList<T>(string storedprocedure, string tablename, string queryFile, int pageIndex, int pageSize, string sqlWhere,
            string sortFile, string srotType, out long count, out string exception, out List<T> list) where T : new()
        {
            list = new List<T>();
            count = 0;
            long total = 0;
            exception = string.Empty;
            list=InitConnction(out exception, WriteAndReadEnum.Read, cmd =>
            {
                List<T> list= new List<T>();
                cmd.CommandText = storedprocedure;
                cmd.CommandType = CommandType.StoredProcedure;

                MySqlParameter table_name = new MySqlParameter("p_table_name", MySqlDbType.VarChar);
                table_name.Direction = ParameterDirection.Input;
                table_name.Value = tablename;

                MySqlParameter files = new MySqlParameter("p_files", MySqlDbType.VarChar);
                files.Direction = ParameterDirection.Input;
                files.Value = queryFile;

                MySqlParameter curr_page = new MySqlParameter("p_curr_page", MySqlDbType.Int32);
                curr_page.Direction = ParameterDirection.Input;
                curr_page.Value = pageIndex;

                MySqlParameter page_size = new MySqlParameter("p_page_size", MySqlDbType.Int32);
                page_size.Direction = ParameterDirection.Input;
                page_size.Value = pageSize;

                MySqlParameter order_string = new MySqlParameter("p_order_string", MySqlDbType.VarChar);
                order_string.Direction = ParameterDirection.Input;
                order_string.Value = "order by " + sortFile;

                MySqlParameter ordertype_string = new MySqlParameter("p_ordertype_string", MySqlDbType.VarChar);
                ordertype_string.Direction = ParameterDirection.Input;
                ordertype_string.Value = string.IsNullOrEmpty(srotType) ? "desc" : srotType;

                MySqlParameter where_string = new MySqlParameter("p_where_string", MySqlDbType.VarChar);
                where_string.Direction = ParameterDirection.Input;
                where_string.Value = sqlWhere;

                MySqlParameter total_rows = new MySqlParameter("p_total_rows", MySqlDbType.Int32);
                total_rows.Direction = ParameterDirection.Output;

                cmd.Parameters.AddRange(new MySqlParameter[] { table_name, files, curr_page, page_size, order_string, ordertype_string, where_string, total_rows });

                var item = cmd.ExecuteReader();
                while (item.Read())
                {
                    Type type = typeof(T);
                    T t = new T();
                    foreach (var pi in type.GetPropertiesWithNoQuery())
                    {
                        pi.SetValue(t, item[pi.GetMappingName()] is DBNull ? null : item[pi.GetMappingName()]);
                    }
                    list.Add(t);
                }
                item.Dispose();
                total = Convert.ToInt64(cmd.Parameters["@p_total_rows"].Value);
                return list;
            });
            count = total;
            return string.IsNullOrEmpty(exception) ? true : false;
        }

        /// <summary>
        /// 查询信息列表
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="sqlstr"></param>
        /// <param name="param"></param>
        /// <param name="isproc"></param>
        /// <param name="exception"></param>
        /// <param name="list"></param>
        /// <returns></returns>
        public bool GetList<T>(string sqlstr, object param, bool isproc, out string exception, out List<T> list) where T : new()
        {
            list = new List<T>();
            exception = null;
            var msg = string.Empty;
            var isSuccess = true;
            list = InitConnction<List<T>>(out exception, WriteAndReadEnum.Read, cmd =>
             {
                 var listc = new List<T>();
                 cmd.CommandText = sqlstr;
                 cmd.CommandType = (isproc ? CommandType.StoredProcedure : CommandType.Text);
                 if (!this.parameterCom(cmd, param, SqlParamsType.Default))
                 {
                     msg = "参数错误";
                     isSuccess = false;
                 }
                 var item = cmd.ExecuteReader();
                 while (item.Read())
                 {
                     Type type = typeof(T);
                     T t = new T();
                     foreach (var pi in type.GetPropertiesWithNoQuery())
                     {
                         pi.SetValue(t, item[pi.GetMappingName()] is DBNull ? null : item[pi.GetMappingName()]);
                     }
                     listc.Add(t);
                 }
                 return listc;
             });
            if (!string.IsNullOrEmpty(msg))
            {
                exception += msg;
                isSuccess = false;
            }
            return isSuccess;
        }

        /// <summary>
        /// DataTable
        /// </summary>
        /// <param name="sqlstr"></param>
        /// <param name="param"></param>
        /// <param name="isproc"></param>
        /// <param name="exception"></param>
        /// <param name="dataTable"></param>
        /// <returns></returns>
        public bool GetDataTable(string sqlstr, object param, bool isproc, out string exception, out DataTable dataTable)
        {
            dataTable = null;
            exception = null;
            var msg = string.Empty;
            var isSuccess = true;
            dataTable = InitConnction(out exception, WriteAndReadEnum.Read, cmd =>
            {
                DataTable dt = new DataTable();
                cmd.CommandText = sqlstr;
                cmd.CommandType = (isproc ? CommandType.StoredProcedure : CommandType.Text);
                if (!this.parameterCom(cmd, param, SqlParamsType.Default))
                {
                    msg = "参数错误";
                    isSuccess = false;
                }
                dt.Load(cmd.ExecuteReader());
                return dt;
            });
            if (!string.IsNullOrEmpty(msg))
            {
                exception += msg;
                isSuccess = false;
            }
            return isSuccess;
        }

        /// <summary>
        /// DataSet
        /// </summary>
        /// <param name="sqlstr"></param>
        /// <param name="param"></param>
        /// <param name="isproc"></param>
        /// <param name="exception"></param>
        /// <param name="dataSet"></param>
        /// <returns></returns>
        public bool GetDataSet(string sqlstr, object param, bool isproc, out string exception, out DataSet dataSet)
        {
            dataSet = null;
            exception = null;
            var msg = string.Empty;
            var isSuccess = true;
            dataSet = InitConnction(out exception, WriteAndReadEnum.Read, cmd =>
            {
                DataSet ds = new DataSet();
                cmd.CommandText = sqlstr;
                cmd.CommandType = (isproc ? CommandType.StoredProcedure : CommandType.Text);
                if (!this.parameterCom(cmd, param, SqlParamsType.Default))
                {
                    msg = "参数错误";
                    isSuccess = false;
                }
                using (MySqlDataAdapter mySqlDataAdapter = new MySqlDataAdapter(cmd))
                {
                    mySqlDataAdapter.Fill(ds);
                }
                return ds;
            });
            if (!string.IsNullOrEmpty(msg))
            {
                exception += msg;
                isSuccess = false;
            }
            return isSuccess;
        }

        /// <summary>
        /// ExecuteNonQuery
        /// </summary>
        /// <param name="sqlstr"></param>
        /// <param name="param"></param>
        /// <param name="cURDModel"></param>
        /// <param name="isproc"></param>
        /// <param name="exception"></param>
        /// <returns></returns>
        public int ExecuteNonQuery(string sqlstr, object param, CURDModel cURDModel, bool isproc, out string exception)
        {
            exception = null;
            int result = -1;
            var msg = string.Empty;
            result = InitConnction(out exception, WriteAndReadEnum.Write, cmd =>
               {
                   int result = -1;
                   using (var tran = cmd.Connection.BeginTransaction())
                   {
                       cmd.Transaction = tran;
                       cmd.CommandText = sqlstr;
                       cmd.CommandType = (isproc ? CommandType.StoredProcedure : CommandType.Text);
                       if (!this.parameterCom(cmd, param, cURDModel.sqlParamsType))
                       {
                           msg = "参数错误";
                           result = -1;
                       }
                       else
                       {
                           result = cURDModel.cUDType == CUDType.Add ? Convert.ToInt32(cmd.ExecuteScalar()) : cmd.ExecuteNonQuery();
                           if (result < 0)
                           {
                               if (tran != null)
                                   tran.Rollback();
                           }
                           else
                           {
                               tran.Commit();
                           }
                       }
                   }
                   return result;
               });
            return result;
        }

        /// <summary>
        /// ExecuteScalar
        /// </summary>
        /// <param name="sqlstr"></param>
        /// <param name="param"></param>
        /// <param name="isproc"></param>
        /// <param name="exception"></param>
        /// <param name="result"></param>
        /// <returns></returns>
        public bool ExecuteScalar(string sqlstr, object param, bool isproc, out string exception, out object result)
        {
            exception = null;
            result = null;
            var msg = string.Empty;
            var isSuccess = true;
            result = InitConnction(out exception, WriteAndReadEnum.Read, cmd =>
              {
                  cmd.CommandText = sqlstr;
                  cmd.CommandType = (isproc ? CommandType.StoredProcedure : CommandType.Text);
                  if (!this.parameterCom(cmd, param, SqlParamsType.Default))
                  {
                      msg = "参数错误";
                      isSuccess = false;
                  }
                  return cmd.ExecuteScalar();
              });
            if (!string.IsNullOrEmpty(msg))
            {
                exception += msg;
                isSuccess = false;
            }
            return isSuccess;
        }
    }
}
